<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="roleDialogFormRef" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单权限:">
							<el-tree
								class="menu-data-tree"
								ref="menuRef"
								:data="state.allMenu"
								show-checkbox
								node-key="id"
								:default-expand-all="true"
								:check-strictly="true"
								:props="defaultProps"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(roleDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRoleDialog">
import { nextTick, reactive, ref } from 'vue';
import { roleApi } from '/@/api/sys/role';
import { useMenuApi } from '/@/api/sys/menu';
import msg from '/@/utils/messageUtils';
import { ElTree } from 'element-plus';
import { type FormInstance } from 'element-plus';
// 定义子组件向父组件传值/事件

// 定义变量内容
const roleDialogFormRef = ref<FormInstance>();
const menuRef = ref<InstanceType<typeof ElTree>>();
const state = reactive({
	roleId: '',
	allMenu: [],
	choiceMenuIds: [],
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});
const defaultProps = {
	children: 'children',
	label: 'menuTitle',
};

// 打开弹窗
const openDialog = async (row: RowRoleType) => {
	state.dialog.title = '选择菜单';
	state.dialog.submitTxt = '提交';
	state.dialog.isShowDialog = true;
	state.roleId = row.id;
	await onLoadAllMenus();
	await onLoadChoiceMenuIds();
	await nextTick();
	setCheckedKeys();
};

const onLoadAllMenus = async () => {
	try {
		const { data } = await useMenuApi().getTreeMenus();
		state.allMenu = data;
	} catch (error) {
		msg().error('加载菜单失败');
	}
};

const onLoadChoiceMenuIds = async () => {
	const { data } = await roleApi().menuIds(state.roleId);
	console.log('选择中的菜单: ', data);
	console.log('选择中的菜单-length: ', data.length);
	state.choiceMenuIds = data;
};

const setCheckedKeys = () => {
	console.log('menuRef.value: ', menuRef.value);
	console.log('state.choiceMenuIds.length: ', state.choiceMenuIds.length);
	if (menuRef.value && state.choiceMenuIds.length > 0) {
		// 确保数据类型一致，统一转换为字符串
		// 		:default-checked-keys="state.choiceMenuIds"
		console.log('手动设置选中状态....');
		const checkedKeys = state.choiceMenuIds.map((id) => String(id));
		menuRef.value.setCheckedKeys(checkedKeys);
	}
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
	const checkNodes = menuRef.value!.getCheckedNodes(false, false);
	console.log('checkNodes: ', checkNodes);
	if (checkNodes.length < 1) {
		msg().info('请选择菜单');
	}
	try {
		const menuIds: any = [];
		checkNodes.forEach((e) => {
			menuIds.push(e.id);
		});
		await roleApi().createRoleAndMenuIds({
			id: state.roleId,
			menuIds: menuIds,
		});
		msg().success('操作成功');
		closeDialog();
	} catch (error) {
		msg().error('操作失败，请重新提交');
	}
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-role-dialog-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
}
</style>
